using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.IO;
using System.Collections.Generic;
using System.Collections.Specialized;

public partial class Default2 : System.Web.UI.Page
{
    HtmlForm frmObj;
    DataSet dsConfig = new DataSet();
    DataSet dsePageInfo = new DataSet();
    DataSet dseInputInfo = new DataSet();
    string strPagesetRowID = "";
    string strErrorMessage = "";
    DataRow drPageInfo = null;
    DataTable dtInput = new DataTable();
    string[] ChartWithXYAxes = { "area", "bar", "column", "line" };
    protected void Page_PreInit(object sender, EventArgs e)
    {
        this.Theme = Session["Theme"].ToString();
        this.Title = "MaxBlox";
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        security hdds = new security();

        if (Session["userid"] == null) Response.Redirect(hdds.SessionExpiryURL);
        if (Session["userid"].ToString() == "") Response.Redirect(hdds.SessionExpiryURL);

        //Code added by Sampath on 18-Nov-2011 for IPP Vertical privilege
        if (Request.QueryString["mn"] != null)
        {
            if (!hdds.checkObjectMenuAccess(Request.QueryString["mn"]))
            {
                showmessage();
                return;
            }
        }

        //Code added by Sampath on 15-Nov-2011 for IPP Vertical privilege
        if (Request.QueryString["PK"] != null && Request.QueryString["pgs_id"] != null)
        {
            if (!hdds.checkRecordAccess(Request.QueryString["PK"].ToString(), Request.QueryString["pgs_id"].ToString()))
            {
                showmessage();
                return;
            }
        }

        if (Request.QueryString["pgs_id"] != null)
        {
            strPagesetRowID = Request.QueryString["pgs_id"];
        }
        if (Request.QueryString["mn"] != null)
            hdds.logMenuClick(Request.QueryString["mn"].ToString());
        if (this.Master.FindControl("Form1") != null)
        {
            frmObj = (HtmlForm)this.Master.FindControl("Form1");

            //if (!Page.IsPostBack)
                //td_widget_ordinates.Style["display"] = "none";

            isAction();

            dsConfig = GetPageSetInfo();
            PageInfoLoad PIL = new PageInfoLoad();
            dsePageInfo = PIL.GetPageSetPageCtrlInfo(strPagesetRowID);
            PIL = null;

            drPageInfo = dsePageInfo.Tables["Page"].Rows[0];

            ShowActionFeature(dsePageInfo);
            if (!Page.IsPostBack)
            {
                LoadSourceType(dsConfig);
                LoadLegendPosition(dsConfig);
                LoadChartType(dsConfig);
                LoadLabelDisplay(dsConfig); // Added by 'Imran Gani' on 13-Aug-2014, for Dashboard widget property
                if (Request.QueryString["PK"] == null)
                {
                    SetDefaultItems();
                    GenerateOrdinates(lst_X_axis.Items, lst_Y_axis.Items);
                }
            }

            CheckEditOperation();
            // Added by srivatsan
            ddlChartType.Attributes.Add("OnChange", "javascript:showicon();");

            isViewmode();
            string strPK = "";
            if (Request.QueryString["PK"] != null)
            {
                strPK = Request.QueryString["PK"].ToString();
            }

            imgowner.Attributes.Add("onclick", "javascript:openlookupwindow('hfOwner','txtOwner','f496930dfe0b690f','" + strPK + "','" + HttpContext.Current.Request.QueryString["pgs_id"].ToString() + "');");
            if (!Page.IsPostBack)
            {
                if (Request.QueryString["PK"] == null || Request.QueryString["CPY"] != null)
                {
                    txtOwner.Text = Session["userid"].ToString();
                    hfOwner.Value = Session["user_afrowid"].ToString();
                    if (Request.QueryString["CPY"] == null)
                    {
                        chkActive.Checked = true;
                        ChkShowLegend.Checked = true;
                    }
                }
            }

            setHeaderText();

            LoadEditPage LEP = new LoadEditPage();
            if (Page.IsPostBack)
            {
                if (Request.QueryString["VMODE"] == null)
                {
                    AddOrdinates();
                    DeleteOrdinates();
                    SetDefaultItems();
                    if (CheckIFSourceChanged())
                        ResetItems();
                    GenerateOrdinates(lst_X_axis.Items, lst_Y_axis.Items);
                }
            }
        }
    }

    private void showmessage()
    {
        try
        {
            lblmessage.Text = wrapItAsMessage("<img src=\"Images/info.gif\" alt=\"\"></img>&nbsp;You do not have sufficient access permission.", true);
            tblbtnbottom.Visible = false;
            tblbtntop.Visible = false;
            pnlDesigner.Visible = false;
            PnlPreview.Visible = false;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("showmessage: Error: " + ex.Message);
        }
    }

    private DataSet GetPageSetInfo()
    {
        DataSet ds = new DataSet();
        HDDatabase HDD = new HDDatabase();
        try
        {
            string sql = "select * from sy_acr_mem where acr_id = 'be456d9eb79818ba'";
            ds.Tables.Add(HDD.GetDataTable(sql, "Config").Copy());
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : GetPageSetInfo: " + ex.Message);
        }
        finally
        {
            HDD = null;
        }
        return ds;
    }

    /// <summary>
    /// Loads Source type in Drop Down from Dataset
    /// </summary>
    /// <param name="dsConfig"></param>
    private void LoadSourceType(DataSet dsConfig)
    {
        try
        {
            if (dsConfig != null)
                if (dsConfig.Tables.Count > 0)
                    if (dsConfig.Tables["Config"] != null)
                        if (dsConfig.Tables["Config"].Rows.Count > 0)
                        {
                            DataRow[] drselect = dsConfig.Tables["Config"].Select("mem_id = 'ST' and mem_value2='True'", "mem_seq asc");
                            if (drselect.Length > 0)
                            {
                                foreach (DataRow dr in drselect)
                                {
                                    ddlSourceType.Items.Add(dr["mem_value1"].ToString());
                                }
                            }
                            LoadSource(ddlSourceType.SelectedValue);
                        }
        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Error : LoadLegendPosition : "+ ex.Message);
        }
    }

    /// <summary>
    /// Loads Legend position in Drop Down from Dataset
    /// </summary>
    /// <param name="dsConfig"></param>
    private void LoadLegendPosition(DataSet dsConfig)
    {
        try
        {
            if (dsConfig != null)
                if (dsConfig.Tables.Count > 0)
                    if (dsConfig.Tables["Config"] != null)
                        if (dsConfig.Tables["Config"].Rows.Count > 0)
                        {
                            DataRow[] drselect = dsConfig.Tables["Config"].Select("mem_id = 'LP'", "mem_seq asc");
                            if (drselect.Length > 0)
                            {
                                foreach (DataRow dr in drselect)
                                {
                                    ddlLegendPosition.Items.Add(dr["mem_value1"].ToString());
                                }
                            }
                        }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : LoadSourceType : " + ex.Message);
        }
    }


    /// <summary>
    /// Loads Chart Type in Drop Down from Dataset
    /// </summary>
    /// <param name="dsConfig"></param>
    private void LoadChartType(DataSet dsConfig)
    {
        try
        {
            if (dsConfig != null)
                if (dsConfig.Tables.Count > 0)
                    if (dsConfig.Tables["Config"] != null)
                        if (dsConfig.Tables["Config"].Rows.Count > 0)
                        {
                            DataRow[] drselect = dsConfig.Tables["Config"].Select("mem_id = 'CT' and mem_value2 = 'True'", "mem_seq asc");
                            if (drselect.Length > 0)
                            {
                                foreach (DataRow dr in drselect)
                                {
                                    ddlChartType.Items.Add(new ListItem(dr["mem_value1"].ToString(),dr["mem_value3"].ToString().Trim()));
                                }
                            }
                        }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : LoadSourceType : " + ex.Message);
        }
    }

    /// <summary>
    /// Loads Legend position in Drop Down from Dataset
    /// </summary>
    /// <param name="dsConfig"></param>
    private void LoadLabelDisplay(DataSet dsConfig) // Added by 'Imran Gani' on 13-Aug-2014, for Dashboard widget property
    {
        try
        {
            if (dsConfig != null)
                if (dsConfig.Tables.Count > 0)
                    if (dsConfig.Tables["Config"] != null)
                        if (dsConfig.Tables["Config"].Rows.Count > 0)
                        {
                            DataRow[] drselect = dsConfig.Tables["Config"].Select("mem_id = 'LD'", "mem_seq asc");
                            if (drselect.Length > 0)
                            {
                                foreach (DataRow dr in drselect)
                                {
                                    ddlLabelDisplay.Items.Add(new ListItem(dr["mem_value1"].ToString(), dr["mem_value2"].ToString()));
                                }
                            }
                        }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : LoadSourceType : " + ex.Message);
        }
    }

    private void CheckEditOperation()
    {
        try
        {
            if (Request.QueryString["CPY"] != null)
            {
                if (Request.QueryString["CPY"] == "0")
                {
                    btnSave.Visible = true;
                    btnSaveNew.Visible = true;
                    btnUpdate.Visible = false;

                    btnSaveTop.Visible = true;
                    btnSaveNewTop.Visible = true;
                    btnUpdateTop.Visible = false;
                    GetData(ref dseInputInfo);
                    if (!Page.IsPostBack)
                    {
                        SetData(dseInputInfo);
                        GenerateOrdinates(lst_X_axis.Items, lst_Y_axis.Items);
                    }
                    //DynamicDisplayI DDI = new DynamicDisplayI();
                    //string sUTC_Offset = DDI.getUserSetting("sy_usr", "time_zone", "sy_timezone", "utc_offset", "timezone_id");
                    //showDefaultValues(ref dt, this.Page.Form, sUTC_Offset);
                    //DDI = null;
                }
            }
            else if (Request.QueryString["PK"] == null)
            {
                btnSave.Visible = true;
                btnSaveNew.Visible = true;
                btnUpdate.Visible = false;

                btnSaveTop.Visible = true;
                btnSaveNewTop.Visible = true;
                btnUpdateTop.Visible = false;
            }
            else
            {
                btnUpdate.Visible = true;
                btnSave.Visible = false;
                btnSaveNew.Visible = false;

                btnUpdateTop.Visible = true;
                btnSaveTop.Visible = false;
                btnSaveNewTop.Visible = false;
                GetData(ref dseInputInfo);
                if (!Page.IsPostBack)
                {
                    SetData(dseInputInfo);
                    GenerateOrdinates(lst_X_axis.Items, lst_Y_axis.Items);
                }

            DynamicDisplayI DDI = new DynamicDisplayI();
            string sUTC_Offset = DDI.getUserSetting("sy_usr", "time_zone", "sy_timezone", "utc_offset", "timezone_id");
            showDefaultValues(ref dtInput, this.Page.Form, sUTC_Offset);
            DDI = null;
            }
        }
        catch
        {
        }
    }

    private void SetData(DataSet dseInputInfo)
    {
        HDDatabase HDD = new HDDatabase();
        try
        {
            if (Request.QueryString["PK"] != null)
                if (Request.QueryString["PK"].Trim() != "")
                {
                    //string sql = "select * from sy_widgets where af_row_id = '"+Request.QueryString["PK"].ToString()+"'";
                    //DataTable dt = HDD.GetDataTable(sql);
                    //DataRow drrData = HDD.GetTableRow(sql);
                    if (dseInputInfo != null)
                    {
                        if (dseInputInfo.Tables.Count > 0)
                        {
                            if (dseInputInfo.Tables["p_widgets"] != null)
                            {
                                dtInput = dseInputInfo.Tables["p_widgets"];
                                if (dtInput.Rows.Count > 0)
                                {
                                    DataRow drrData = dtInput.Rows[0];
                                    if (drrData != null)
                                    {
                                        txtDashboardName.Text = drrData["name"].ToString();
                                        txtHeader.Text = drrData["header"].ToString();
                                        txtDescription.Text = drrData["description"].ToString();
                                        chkActive.Checked = drrData["active"].ToString().Trim() != "" ? Convert.ToBoolean(drrData["active"].ToString()) : false;
                                        ddlSourceType.SelectedValue = drrData["source_type"].ToString();

                                        //ddlChartType.SelectedValue = ddlChartType.Items.FindByText(drrData["chart_type"].ToString()).Value;
                                        ddlChartType.SelectedValue = drrData["chart_type"].ToString();
                                        ChkShowLegend.Checked = drrData["show_legend"].ToString().Trim() != "" ? Convert.ToBoolean(drrData["show_legend"].ToString()) : false;
                                        ddlLegendPosition.SelectedValue = drrData["legend_position"].ToString();
                                        txtEmptyChartText.Text = drrData["empty_chart_text"].ToString();
                                        //hfCustodianUser.Value = drrData["custodian_user"].ToString();
                                        //txtCustodianUser.Text = getValueToStore("sy_usr", "user_id", "af_row_id", drrData["custodian_user"].ToString());
                                        ChkIgnoreOwnerSecurity.Checked = drrData["ignore_owner_security"].ToString().Trim() != "" ? Convert.ToBoolean(drrData["ignore_owner_security"].ToString()) : false;
                                        ddlLabelDisplay.SelectedValue = drrData["label_display"].ToString(); // Added by 'Imran Gani' on 13-Aug-2014, for Dashboard widget property
                                        if (ddlChartType.SelectedValue.Contains("pie") || ddlChartType.SelectedValue.Contains("doughnut"))
                                            ddlLabelDisplay.Enabled = true;
                                        else
                                            ddlLabelDisplay.Enabled = false;
                                        txtTextContent.Text = drrData["text_content"].ToString(); // Added by 'Imran Gani' on 05-Sep-2014, for Dashboard Text widget
                                        if (ddlChartType.SelectedValue == "text")
                                        {
                                            lblTextContent.Visible = true;
                                            txtTextContent.Visible = true;
                                            imgTextContentRequired.Visible = true;
                                        }
                                        else
                                        {
                                            lblTextContent.Visible = false;
                                            txtTextContent.Visible = false;
                                            imgTextContentRequired.Visible = false;
                                        }
                                        hfOwner.Value = drrData["owner_id"].ToString();
                                        txtOwner.Text = getValueToStore("sy_usr", "user_id", "af_row_id", drrData["owner_id"].ToString());
                                        hfafrowid.Value = drrData["af_row_id"].ToString();
                                        hfcreatedby.Value = drrData["created_by"].ToString();
                                        hfcreatedat.Value = drrData["created_at"].ToString();

                                        LoadSource(ddlSourceType.SelectedValue);
                                        ddlSource.SelectedValue = drrData["source"].ToString();



                                    }
                                }
                            }
                            if (dseInputInfo.Tables["p_widget_ordinates"] != null)
                            {
                                dtInput = dseInputInfo.Tables["p_widget_ordinates"];
                                if (dtInput.Rows.Count > 0)
                                {
                                    DataRow[] drrXaxis = dtInput.Select("widget='" + Request.QueryString["PK"] + "' and axis_type = 'X'","sequence asc");
                                    if (drrXaxis.Length > 0)
                                    {
                                        for (int i = 0; i < drrXaxis.Length; i++)
                                        {
                                            lst_X_axis.Items.Add(drrXaxis[i]["axis_column"].ToString());
                                        }
                                    }
                                    DataRow[] drrYaxis = dtInput.Select("widget='" + Request.QueryString["PK"] + "' and axis_type = 'Y'","sequence asc");
                                    if (drrYaxis.Length > 0)
                                    {
                                        for (int j = 0; j < drrYaxis.Length; j++)
                                        {
                                            lst_Y_axis.Items.Add(drrYaxis[j]["axis_column"].ToString());
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

            
        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Error : SetData :" + ex.Message);
        }
    }

    private void LoadSource(string type)
    {
        string sql = "";
        DataSet dssource = new DataSet();
        SecurityFilter SF = new SecurityFilter();
        HDDatabase HDD = new HDDatabase();
        try
        {
            if (type.Trim() != "")
            {
                ddlSource.Items.Clear();
                switch (type.ToLower())
                {
                    case "report":
                        sql = "select af_row_id,rpt_name from sy_report order by rpt_name";
                        //dssource = SF.GetFilterDataset(sql);
                        sql = SF.applysecurity(sql);
                        dssource = HDD.GetDataset(sql);
                        if (dssource != null)
                            if (dssource.Tables.Count > 0)
                                if (dssource.Tables[0].Rows.Count > 0)
                                {
                                    ddlSource.DataSource = dssource.Tables[0];
                                    ddlSource.DataTextField = "rpt_name";
                                    ddlSource.DataValueField = "af_row_id";
                                    ddlSource.DataBind();
                                }
                        break;
                    case "query":
                        sql = "select af_row_id,report_base_name from sy_report_sql order by report_base_name";
                        dssource = HDD.GetDataset(sql);
                        if (dssource != null)
                            if (dssource.Tables.Count > 0)
                                if (dssource.Tables[0].Rows.Count > 0)
                                {
                                    ddlSource.DataSource = dssource.Tables[0];
                                    ddlSource.DataTextField = "report_base_name";
                                    ddlSource.DataValueField = "af_row_id";
                                    ddlSource.DataBind();
                                }
                        break;
                    case "object":
                        break;
                    default:
                        break;
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : LoadSource: " + ex.Message);
        }
        finally
        {
            dssource = null;
            SF = null;
        }
    }
    private string wrapItAsMessage(string msg, bool isError)
    {
        return "<div class=\"" + (isError == true ? "mbErrorMessage" : "mbMessage") + "\">" + msg + "</div>";
    }

    protected void ddlSourceType_SelectedIndexChanged(object sender, EventArgs e)
    {
        LoadSource(ddlSourceType.SelectedValue);
        RefreshChartTypeImage();
    }
    protected void btnSaveTop_Click(object sender, EventArgs e)
    {
        if (SaveData())
        {
            string urlNavigate = Navigator.getURL(Request.Url.AbsoluteUri.ToString());
            Response.Redirect(urlNavigate);
        }
        else
        {
            if (strErrorMessage.Trim() != "")
                lblmessage.Text = wrapItAsMessage("<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;"+"Data Insert not successful. "+ strErrorMessage,true);
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (SaveData())
        {
            string urlNavigate = Navigator.getURL(Request.Url.AbsoluteUri.ToString());
            Response.Redirect(urlNavigate);

            
        }
        else
        {
            if (strErrorMessage.Trim() != "")
                lblmessage.Text = wrapItAsMessage("<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;"+"Data Insert not successful. "+ strErrorMessage,true);
        }
    }
    protected void btnSaveNewTop_Click(object sender, EventArgs e)
    {
        if (SaveData())
        {
            string urlNavigate = HttpContext.Current.Request.Url.AbsolutePath + "?pgs_id=" + HttpContext.Current.Request.QueryString["pgs_id"] + "&mn=" + HttpContext.Current.Request.QueryString["mn"];
            Response.Redirect(urlNavigate);
        }
        else
        {
            if (strErrorMessage.Trim() != "")
                lblmessage.Text = wrapItAsMessage("<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;" + "Data Insert not successful. " + strErrorMessage,true);
        }
    }
    protected void btnSaveNew_Click(object sender, EventArgs e)
    {
        if (SaveData())
        {
            string urlNavigate = HttpContext.Current.Request.Url.AbsolutePath + "?pgs_id=" + HttpContext.Current.Request.QueryString["pgs_id"] + "&mn=" + HttpContext.Current.Request.QueryString["mn"];
            Response.Redirect(urlNavigate);
        }
        else
        {
            if (strErrorMessage.Trim() != "")
                lblmessage.Text = wrapItAsMessage("<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;" + "Data Insert not successful. " + strErrorMessage,true);
        }
    }
    protected void btnUpdateTop_Click(object sender, EventArgs e)
    {
        if (UpdateData())
        {
            string urlNavigate = Navigator.getURL(Request.Url.ToString());
            Response.Redirect(urlNavigate);
        }
        else
        {
            if (strErrorMessage.Trim() != "")
                lblmessage.Text = wrapItAsMessage("<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;" + "Data Update not successful. " + strErrorMessage,true);
        }
    }
    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        if (UpdateData())
        {
            string urlNavigate = Navigator.getURL(Request.Url.ToString());
            Response.Redirect(urlNavigate);
        }
        else
        {
            if (strErrorMessage.Trim() != "")
                lblmessage.Text = wrapItAsMessage("<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;" + "Data Update not successful. " + strErrorMessage,true);
        }
    }

    private bool SaveData()
    {
        ScreenReader SR = new ScreenReader();
        bool blnStatus = false;    
        try
        {
            DataSet dsInputInfo = new DataSet();
            if (CaptureData(ref dsInputInfo))
            {
                if (SR.errormessage != "")
                {
                    lblmessage.Text = wrapItAsMessage("<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;" + "Data Insert not successful. Error: " + SR.errormessage,true);
                    return false;
                }

                //function added by bala on 17-Nov-2011 for IPP Tech check 
                //CommonFunctions.encodeData(dsInputInfo);
                Master MA = new Master();
                blnStatus = MA.ProcessOperation(dsePageInfo, dsInputInfo, "INSERT");
                if (blnStatus == false)
                {
                    strErrorMessage = MA.ErrorMessage;
                }
            }
            else
            {
                lblmessage.Text = wrapItAsMessage("<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;" + "Invalid data for Owner: " + txtOwner.Text,true);
                return false;
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : SaveData :" + ex.Message);
        }
        finally
        {
            SR = null;
        }

        return blnStatus;
    }

    private bool UpdateData()
    {
        ScreenReader SR = new ScreenReader();
        bool blnStatus = false;
        try
        {

            DataSet dsInputInfo = new DataSet();
            if (CaptureData(ref dsInputInfo))
            {
                if (SR.errormessage != "")
                {
                    lblmessage.Text = wrapItAsMessage("<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;" + "Data Insert not successful. Error: " + SR.errormessage,true);
                    return false;
                }

                Master MA = new Master();
                if (PerformUpdate(dsePageInfo,dsInputInfo))
                {
                    //function added by bala on 18-Nov-2011 for IPP Tech check 
                    //CommonFunctions.encodeData(dsInputInfo);
                    blnStatus = MA.ProcessOperation(dsePageInfo, dsInputInfo, "INSERT");
                }
                if (blnStatus == false)
                {
                    strErrorMessage = MA.ErrorMessage;
                }
            }
            else
            {
                lblmessage.Text = wrapItAsMessage("<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;" + "Invalid data for Owner: " + txtOwner.Text,true);
                return false;
            }

        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : SaveData :" + ex.Message);
        }
        finally
        {
            SR = null;
        }

        return blnStatus;
    }

    private bool validateOwnerID()
    {
        bool status = true;
        if (txtOwner.Text.Trim() != "")
        {
            string Owner = getValueToStore("sy_usr", "af_row_id", "user_id", txtOwner.Text.Trim());
            if (Owner == "")
            {
                strErrorMessage = "Invalid data for Owner : " + txtOwner.Text;
                lblmessage.Text = wrapItAsMessage("Invalid data for Owner : " + txtOwner.Text,true);
                status = false;
            }
            else
            {
                hfOwner.Value = Owner;
                status = true;
            }
        }
        else
        {
            hfOwner.Value = "";
        }
        return status;

    }

    private bool CaptureData(ref DataSet dseInputInfo)
    {
        HDDatabase HDD = new HDDatabase();
        bool status = false;
        if (validateOwnerID())
        {
            PageInfoLoad PIL = new PageInfoLoad();
            dsePageInfo = PIL.GetPageSetPageCtrlInfo(strPagesetRowID);

            DataTable dtaPageSet = dsePageInfo.Tables["PageSet"];
            DataTable dtaPage = dsePageInfo.Tables["Page"];
            DataTable dtaPageKeys = dsePageInfo.Tables["PageKeys"];
            DataTable dtaPageCtrl = dsePageInfo.Tables["PageCtrl"];

            drPageInfo = dsePageInfo.Tables["Page"].Rows[0];
            DataSet dsPageInfo1 = PIL.GetPageSetPageCtrlInfo("b50700253c3beb0c"); // widget_ordinates
            dsePageInfo.Tables["Page"].Merge(dsPageInfo1.Tables["Page"]);
            dsePageInfo.Tables["PageCtrl"].Merge(dsPageInfo1.Tables["PageCtrl"]);
            dsePageInfo.Tables["PageKeys"].Merge(dsPageInfo1.Tables["PageKeys"]);


            ScreenReader SR = new ScreenReader();
            if (dseInputInfo.Tables.Contains(dtaPage.Rows[0]["page_id"].ToString()) == false)
                SR.CreatePageDataTable(dseInputInfo, dtaPage, dtaPageCtrl);

            if (dseInputInfo.Tables["p_widgets"] != null)
            {
                DataRow drdata = dseInputInfo.Tables[dtaPage.Rows[0]["page_id"].ToString()].NewRow();

                drdata["name"] = txtDashboardName.Text;
                drdata["header"] = txtHeader.Text;
                drdata["description"] = txtDescription.Text;
                drdata["active"] = chkActive.Checked;
                drdata["source_type"] = ddlSourceType.SelectedValue;
                drdata["source"] = ddlSource.SelectedValue;
                drdata["chart_type"] = ddlChartType.SelectedValue;
                drdata["show_legend"] = ChkShowLegend.Checked;
                drdata["legend_position"] = ddlLegendPosition.SelectedValue;
                drdata["empty_chart_text"] = txtEmptyChartText.Text;
                //drdata["custodian_user"] = hfCustodianUser.Value;
                drdata["ignore_owner_security"] = ChkIgnoreOwnerSecurity.Checked;
                drdata["label_display"] = ddlLabelDisplay.SelectedValue; // Added by 'Imran Gani' on 13-Aug-2014, for Dashboard widget property
                drdata["text_content"] = txtTextContent.Text; // Added by 'Imran Gani' on 05-Sep-2014, for Dashboard Text widget
                drdata["owner_id"] = hfOwner.Value;

                if (Request.QueryString["PK"] == null || Request.QueryString["CPY"] != null)
                {
                    hfafrowid.Value = SR.getHashKey();
                    drdata["af_row_id"] = hfafrowid.Value;
                    drdata["created_by"] = Session["user_afrowid"].ToString();
                    drdata["modified_by"] = Session["user_afrowid"].ToString();
                    drdata["created_at"] = DateTime.UtcNow;
                    drdata["modified_at"] = DateTime.UtcNow;
                }
                else
                {
                    drdata["af_row_id"] = hfafrowid.Value;
                    drdata["created_by"] = hfcreatedby.Value;
                    drdata["modified_by"] = Session["user_afrowid"].ToString();
                    drdata["created_at"] = hfcreatedat.Value;
                    drdata["modified_at"] = DateTime.UtcNow;
                }

                if (drdata != null)
                    dseInputInfo.Tables[dtaPage.Rows[0]["page_id"].ToString()].Rows.Add(drdata);
            }
            //string type = ddlChartType.SelectedValue; // Commanded by 'Imran Gani' on 10-Oct-2012, To get axis for all charts
            //if (ValidateForAxes(type))
            //{
                if (dseInputInfo.Tables["p_widget_ordinates"] != null)
                {
                    DataTable dt = null;
                    if (Request.QueryString["PK"] != null)
                        dt = HDD.GetDataTable("select * from sy_widget_ordinates where widget= '" + hfafrowid.Value + "'");
                    if (lst_X_axis.Items.Count > 0)
                    {

                        for (int i = 0; i < lst_X_axis.Items.Count; i++)
                        {
                            DataRow drrData = dseInputInfo.Tables["p_widget_ordinates"].NewRow();

                            drrData["widget"] = hfafrowid.Value;
                            drrData["axis_type"] = "X";
                            drrData["axis_column"] = lst_X_axis.Items[i].Value;
                            drrData["sequence"] = i;
                            drrData["active"] = true;
                            drrData["owner_id"] = hfOwner.Value;
                            if (Request.QueryString["PK"] == null || Request.QueryString["CPY"] != null)
                            {
                                drrData["af_row_id"] = SR.getHashKey();
                                drrData["created_by"] = Session["user_afrowid"].ToString();
                                drrData["modified_by"] = Session["user_afrowid"].ToString();
                                drrData["created_at"] = DateTime.UtcNow;
                                drrData["modified_at"] = DateTime.UtcNow;
                            }
                            else
                            {
                                DataRow[] drr = dt.Select("axis_column='" + lst_X_axis.Items[i].Value + "' and axis_type='X'");
                                if (drr.Length > 0)
                                    drrData["af_row_id"] = drr[0]["af_row_id"].ToString();
                                else
                                    drrData["af_row_id"] = SR.getHashKey();
                                drrData["created_by"] = hfcreatedby.Value;
                                drrData["modified_by"] = Session["user_afrowid"].ToString();
                                drrData["created_at"] = hfcreatedat.Value;
                                drrData["modified_at"] = DateTime.UtcNow;
                            }

                            dseInputInfo.Tables["p_widget_ordinates"].Rows.Add(drrData);

                        }
                    }
                    if (lst_Y_axis.Items.Count > 0)
                    {
                        for (int i = 0; i < lst_Y_axis.Items.Count; i++)
                        {
                            DataRow drrData = dseInputInfo.Tables["p_widget_ordinates"].NewRow();

                            drrData["widget"] = hfafrowid.Value;
                            drrData["axis_type"] = "Y";
                            drrData["axis_column"] = lst_Y_axis.Items[i].Value;
                            drrData["sequence"] = i;
                            drrData["active"] = true;
                            drrData["owner_id"] = hfOwner.Value;
                            if (Request.QueryString["PK"] == null || Request.QueryString["CPY"] != null)
                            {
                                drrData["af_row_id"] = SR.getHashKey();
                                drrData["created_by"] = Session["user_afrowid"].ToString();
                                drrData["modified_by"] = Session["user_afrowid"].ToString();
                                drrData["created_at"] = DateTime.UtcNow;
                                drrData["modified_at"] = DateTime.UtcNow;
                            }
                            else
                            {
                                DataRow[] drr = dt.Select("axis_column='" + lst_Y_axis.Items[i].Value + "' and axis_type ='Y'");
                                if (drr.Length > 0)
                                    drrData["af_row_id"] = drr[0]["af_row_id"].ToString();
                                else
                                    drrData["af_row_id"] = SR.getHashKey();
                                drrData["created_by"] = hfcreatedby.Value;
                                drrData["modified_by"] = Session["user_afrowid"].ToString();
                                drrData["created_at"] = hfcreatedat.Value;
                                drrData["modified_at"] = DateTime.UtcNow;
                            }

                            dseInputInfo.Tables["p_widget_ordinates"].Rows.Add(drrData);
                        }
                    }
                }
            //}
            status = true;
        }
        else
        {
            status = false;
        }
        return status;
    }

    private String getValueToStore(String TableName, String ColumnName1, String ColumnName2, String Value)
    {
        String sReturn = "";
        HDDatabase HDD = null;
        if (Value != "")
        {
            HDD = new HDDatabase();
            sReturn = HDD.GetColumnValue("Select " + ColumnName1 + " from " + TableName + " where " + ColumnName2 + "='" + Value.Replace("'", "''") + "'");
            HDD = null;
        }
        return sReturn;
    }
    private void isViewmode()
    {
        if (Request.QueryString["VMODE"] != null)
        {
            if (Request.QueryString["VMODE"].ToString() == "1")
            {
                DynamicDisplayI DDI = new DynamicDisplayI();
                DDI.disableControls(this);

                imgowner.Visible = false;
                //imgCustodian.Visible = false;
                //btnSave.Visible = false;
                //btnSaveTop.Visible = false;
                //btnSaveNew.Visible = false;
                //btnSaveNewTop.Visible = false;
                //btnUpdate.Visible = false;
                //btnUpdateTop.Visible = false;
                //btnReset.Visible = false;
                //btnResetTop.Visible = false;

                pnlDesigner.Visible = false;
                PnlPreview.Visible = true;
                PreviewDashboard();
            }
        }
    }
    protected void btnResetTop_Click(object sender, EventArgs e)
    {
        Reset();
    }
    protected void btnReset_Click(object sender, EventArgs e)
    {
        Reset();
    }

    private void Reset()
    {
        string url = Request.Url.ToString();
        Response.Redirect(url);
    }

    private void PreviewDashboard()
    {
        Dashboards DB = new Dashboards();
        try
        {
            if (Request.QueryString["PK"] != null)
            {
                DB.GenerateWidgets(Request.QueryString["PK"].ToString(), ref tdPreview, true,frmObj,false);
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : PreviewDashboard :" + ex.Message);
        }
        finally
        {
            DB = null;
        }
    }
    private bool isAction() //Added by srivatsan for Actions
    {
        bool status = false;
        try
        {
            if (Request.QueryString["action"] != null)
            {
                if (Request.QueryString["action"].ToString().Trim() == "1")
                {
                    status = true;
                    NameValueCollection querystring = HttpUtility.ParseQueryString(Request.UrlReferrer.Query);
                    string strPagesetRowId = querystring["pgs_id"];
                    string strMenuRowId = querystring["mn"];
                    string strPK = Request.QueryString["ID"].ToString();
                    string temp = querystring["test"];
                    if (Request.QueryString["Vmode"] != null)
                    {
                        //Response.Redirect("ReportWizard.aspx?pgs_id=" + strPagesetRowId + "&PK=" + strPK + "&mn=" + strMenuRowId + "&vmode=1");
                        string redirect = "WidgetDesigner.aspx?pgs_id="+strPagesetRowId+"&mn="+strMenuRowId+"&PK=" + strPK + "&vmode=1";
                        Response.Redirect(redirect);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : isAction :" + ex.Message);
        }
        return status;
    }

    // Added by srivatsan on Dec 03 2009 to enable action feature
    private void ShowActionFeature(DataSet dsePageInfo)
    {
        Action action = new Action();
        try
        {

            if (Request.QueryString["PK"] != null)
            {
                if (Request.QueryString["CPY"] == null)
                {
                    if (dsePageInfo != null)
                        if (dsePageInfo.Tables.Count > 0)
                            if (dsePageInfo.Tables.Contains("Page Actions"))
                            {
                                DataRow[] drractions = dsePageInfo.Tables["Page Actions"].Select();
                                if (drractions.Length > 0)
                                {
                                    HtmlTableCell htc = (HtmlTableCell)Form.FindControl("td_action_div");
                                    HtmlTableCell htcheader = (HtmlTableCell)Form.FindControl("td_action");
                                    action.CreateActionImage("img_action_header", ref htcheader);
                                    action.CreateActionDIV(ref htc, drractions, "img_action_header", Request.QueryString["PK"].ToString(), true);
                                }
                            }
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : ShowActionFeature : " + ex.Message);
        }
        finally
        {
            action = null;
        }
    }

    private void setHeaderText()
    {
        if (Request.QueryString["PK"] != null)
        {
            lblheader.Text = "Widget Designer - Edit";
        }
        else
        {
            lblheader.Text = "Widget Designer - Add";
        }
        if (Request.QueryString["CPY"] != null)
        {
            lblheader.Text = "Widget Designer - Copy";
        }
        if (Request.QueryString["Vmode"] != null)
        {
            lblheader.Text = "Widget Designer - View";
        }

        if (drPageInfo != null)
            AddPageToolTip(drPageInfo, ref lblheader);

    }

    private void AddPageToolTip(DataRow drpage, ref Label lblHeader)
    {
        if (drpage != null)
        {
            //if(!Page.IsPostBack)
            lblHeader.Text = lblHeader.Text + getTootipIcon(drpage);
            Literal lit = new Literal();
            lit.Text = getTooltipContent(drpage);
            td_Page_ToopTip.Controls.Add(lit);
        }
    }
    private string getTootipIcon(DataRow droPage)
    {
        try
        {
            if (!droPage.Table.Columns.Contains("page_desc")) return "";
            if (droPage["page_desc"].ToString().Trim() == "") return "";
            return "&nbsp;<img id=\"page_tooltip_img\" style=\"cursor:pointer;\" src=\"Images/collapse3.gif\" onClick=\"javascript:showHideTooltipDIV();\" border=\"0\"></img>";
        }
        catch (Exception e)
        {
            return "";
        }
    }

    private string getTooltipContent(DataRow droPage)
    {
        if (!droPage.Table.Columns.Contains("page_desc")) return "";
        if (droPage["page_desc"].ToString().Trim() == "") return "";
        //string ret = "";
        //ret = "<div id=\"page_tooltip_div\" style=\"border-bottom:solid 1px #000000;\">";
        //ret += "<table border=\"0\" cellpadding=\"5\" cellspacing=\"0\" width=\"100%\"><tr><td width=\"10%\" valign=\"center\" align=\"center\"><img src=\"Images/info.gif\" border=\"0\"></img></td><td width=\"80%\" class=\"controlFont\">";
        //ret += droPage["page_desc"].ToString();
        //ret += "</td></tr></table>";
        //ret +="</div>";
        return getContent(HttpContext.Current.Server.MapPath("") + @"\scripts\pagetooltipcontent.txt").Replace("<<content>>", CommonFunctions.SafeEncode(droPage["page_desc"].ToString()));
    }

    private string getContent(string fileName)
    {
        try
        {
            if (!File.Exists(fileName))
                return "";
            string temp = "";
            StreamReader sr = new StreamReader(fileName);
            temp = sr.ReadToEnd();
            sr.Close();
            sr = null;
            return temp;
        }
        catch (Exception e)
        {
            return "";
        }
    }

    private void showDefaultValues(ref DataTable dtData, HtmlForm frmObj, string sUTC_Offset)//implemented by sanal on 08 April 2008
    {
        if (HttpContext.Current.Request.QueryString["CPY"] != null)
        {
            if (HttpContext.Current.Request.QueryString["CPY"] == "0")
            {
                return;
            }
        }
        if (dtData == null) return;
        if (dtData.Rows.Count < 1) return;
        if (!dtData.Columns.Contains("created_by")) return;
        if (!dtData.Columns.Contains("modified_at")) return;
        DynamicDisplayI DDI = new DynamicDisplayI();
        try
        {
            HtmlTable ht = new HtmlTable();
            HtmlTableRow htr = new HtmlTableRow();

            //HDDatabase hdd = new HDDatabase();
            //string userDisplayField = hdd.GetColumnValue("sy_acr_mem", "mem_id", "af_row_id='30583eb791cb7d5b'");
            //userDisplayField = userDisplayField.Trim().Length==0 ? "user_id" : userDisplayField;
            //string userName = hdd.GetColumnValue("sy_usr", userDisplayField, "af_row_id='" + dtData.Rows[0]["created_by"].ToString() + "'");
            string userName = getUserName(dtData.Rows[0]["created_by"].ToString()); //hdd.GetColumnValue("sy_usr", userDisplayField, "af_row_id='" + dtData.Rows[0]["created_by"].ToString() + "'");
            //hdd = null;


            HtmlTableCell htc = new HtmlTableCell();
            if (userName.Trim().Length > 0)
            {
                //htc.Controls.Add(new LiteralControl("<b>Owner:</b>&nbsp;" + userName));
                // Added by srivatsan on June 15 2009 for owner id field
                htc.Controls.Add(new LiteralControl("<b>Created By:</b>&nbsp;" + userName));
                htc.Width = "50%";
                htr.Cells.Add(htc);
                //ht.Rows.Add(htr);
            }
            userName = null;

            htc = new HtmlTableCell();
            //DateTime dt = DateTime.Parse(dtData.Rows[0]["modified_at"].ToString());
            //string dat = DDI.getUsersDT(dtData.Rows[0]["modified_at"].ToString(), sUTC_Offset);
            Localization ll = new Localization();
            //htc.Controls.Add(new LiteralControl("<b>Last updated at:</b>&nbsp;" + dt.ToLocalTime().ToString("dd-MMM-yyyy hh:mm:ss tt")));
            htc.Controls.Add(new LiteralControl("<b>Last updated at:</b>&nbsp;" + ll.getDateTime4TimeZone(dtData.Rows[0]["modified_at"].ToString(), sUTC_Offset, false, true)));
            ll = null;
            htc.Width = "50%";
            htc.Align = "center";
            htr.Cells.Add(htc);

            ht.Rows.Add(htr);
            htr.Attributes.Add("Class", "Dynamic_HtmlTableCell");

            HtmlTableCell htcObj = (HtmlTableCell)DDI.FindControl(frmObj.Controls, "tdcDefaultFields");
            ht.Width = "100%";
            ht.Border = 0;
            ht.CellPadding = 0;
            ht.CellSpacing = 0;
            ht.EnableViewState = false;
            htcObj.Controls.Add(ht);
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in showDefaultValues function. Error: " + e.Message);
        }
        finally
        {
            DDI = null;
        }
    }
    private string getUserName(string rowid)
    {
        HDDatabase hdd = new HDDatabase();
        DataTable dt = new DataTable();
        string ret = "";
        try
        {
            string userDisplayField = hdd.GetColumnValue("sy_acr_mem", "mem_id", "af_row_id='30583eb791cb7d5b'");
            userDisplayField = userDisplayField.Trim().Length == 0 ? "user_id" : userDisplayField;
            dt = hdd.GetDataTable("select " + userDisplayField + " from sy_usr where af_row_id='" + rowid + "'");
            if (dt != null)
                if (dt.Rows.Count > 0)
                    ret = dt.Rows[0][0].ToString();
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in getUserName : " + e.ToString());
        }
        finally
        {
            hdd = null;
            dt = null;
        }
        return ret;
    }

    private void GetData(ref DataSet dseInputInfo)
    {
        HDDatabase HDD = new HDDatabase();
        try
        {
            if (Request.QueryString["PK"] != null)
            {
                string sql = "select * from sy_widgets where af_row_id = '"+Request.QueryString["PK"]+"'";
                dtInput = HDD.GetDataTable(sql,"p_widgets");
                if (dtInput != null)
                    dseInputInfo.Tables.Add(dtInput.Copy());
                sql = "select * from sy_widget_ordinates where widget = '" + Request.QueryString["PK"] + "'";
                dtInput = HDD.GetDataTable(sql,"p_widget_ordinates");
                if (dtInput != null)
                    dseInputInfo.Tables.Add(dtInput.Copy());
                //function added by Bala on 17-Nov-2011 for IPP Tech check 
                //CommonFunctions.decodeData(dseInputInfo);
            }
        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Error : GetData :"+ ex.Message);
        }
        finally
        {
            HDD = null;
        }
    }

    #region Widget Ordinates
    private void GenerateOrdinates(ListItemCollection Xaxis,ListItemCollection Yaxis)
    {
        Dashboards dbs = new Dashboards();
        try
        {
            if (ddlSource.SelectedIndex > -1)
                if (ddlSourceType.SelectedIndex > -1)
                {
                    string strSourceType = ddlSourceType.SelectedValue;
                    string strSourceID = ddlSource.SelectedValue;
                    string strWidgetQuery = "";
                    DataTable dtWidgetData = new DataTable();
                    DataTable dtColumns = new DataTable();
                    Hashtable htColumns = new Hashtable();
                    dbs.GetWidgetQuery(strSourceType, strSourceID, ref strWidgetQuery, ref dtWidgetData, frmObj, ref htColumns);
                    dtColumns = GetChartColumns(htColumns);
                    if (dtColumns.Rows.Count > 0)
                    {
                        if (!Page.IsPostBack)
                        {
                            if (Request.QueryString["PK"] == null)
                            {
                                if (lst_X_axis.Items.Count > 0)
                                {
                                    lst_X_axis.Items[0].Value = dtColumns.Rows[0]["Val"].ToString();
                                    lst_X_axis.Items[0].Text = dtColumns.Rows[0]["Fld"].ToString();
                                    lst_Y_axis.Items[0].Value = dtColumns.Rows[0]["Val"].ToString();
                                    lst_Y_axis.Items[0].Text = dtColumns.Rows[0]["Fld"].ToString();
                                }
                                else
                                {
                                    lst_X_axis.Items.Add(new ListItem(dtColumns.Rows[0]["Fld"].ToString(), dtColumns.Rows[0]["Val"].ToString()));
                                    lst_Y_axis.Items.Add(new ListItem(dtColumns.Rows[0]["Fld"].ToString(), dtColumns.Rows[0]["Val"].ToString()));
                                }
                                Xaxis = lst_X_axis.Items;
                                Yaxis = lst_Y_axis.Items;
                            }
                        }
                        RenderOrdinates(Xaxis, Yaxis, dtColumns, dtColumns);
                    }
                    else
                    {
                        lblmessage.Text = wrapItAsMessage("Select a valid source",true);
                    }
                }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("WidgetDesigner : GenerateOrdinates :" + ex.Message);
        }
        finally
        {
            dbs = null;
        }
    }

    private DataTable GetChartColumns(Hashtable htcolumns)
    {
        DataTable dt = null;
        try
        {
            dt = new DataTable();
            dt.Columns.Add("Val");
            dt.Columns.Add("Fld");
            if (htcolumns.Count > 0)
            {
                foreach (string str in htcolumns.Keys)
                {
                    dt.Rows.Add(str, htcolumns[str].ToString());
                }

                DataRow[] drr = dt.Select("", "Fld asc");
                if (drr.Length > 0)
                {
                    DataTable dtSorter = dt.Clone();
                    for (int i = 0; i < drr.Length; i++)
                    {
                        dtSorter.ImportRow(drr[i]);
                    }
                    dt = dtSorter;
                }
            }
        }
        catch
        { 

        }
        return dt;
    }

    private void RenderOrdinates(ListItemCollection  Xordinates,ListItemCollection YOrdinates,DataTable XList,DataTable YList)
    {
        HtmlTable htOrdinates = new HtmlTable();
        HtmlTableRow htrOrdinates = new HtmlTableRow();
        HtmlTableCell htcOrdinates = new HtmlTableCell();
        try
        {

            htOrdinates.Width = "100%";
            htOrdinates.CellPadding = 0;
            htOrdinates.CellSpacing = 0;
            htOrdinates.Border = 0;
            //htOrdinates.BorderColor = "LightGray";
            

            htrOrdinates = new HtmlTableRow();
            htcOrdinates = new HtmlTableCell();
            htcOrdinates.Height = "5px";
            htcOrdinates.ColSpan = 6;
            htrOrdinates.Controls.Add(htcOrdinates);
            htOrdinates.Controls.Add(htrOrdinates);

            //Header Row
            htrOrdinates = new HtmlTableRow();
            htcOrdinates = new HtmlTableCell();
            htcOrdinates.ColSpan = 6;
            htrOrdinates.Attributes.Add("class", "pgForm_title");
            Label lblHeader = new Label();
            lblHeader.Text = "Select Chart Co-ordinates";

            htcOrdinates.Controls.Add(lblHeader);
            htrOrdinates.Controls.Add(htcOrdinates);
            htOrdinates.Controls.Add(htrOrdinates);
            // End of Header Row


            // Ordinates Content
            htrOrdinates = new HtmlTableRow();
            htrOrdinates.Attributes.Add("class", "Grid_Row1");

            //if (YOrdinates.Count > 0) // There exist atleast a single ordinates
            //{
                //if (Xordinates.Count > 0)
                //{
            int YLength = 1;
            if (YOrdinates.Count > 0)
                YLength = YOrdinates.Count;
                    for (int i = 0; i < YLength; i++)
                    {
                        htrOrdinates = new HtmlTableRow();
                        htrOrdinates.Attributes.Add("class", "Grid_Row1");
                        if (i == 0)
                        {
                            //X ordinate Label
                            htcOrdinates = new HtmlTableCell();
                            Label lbl = new Label();
                            lbl.CssClass = "controlLabelFont";
                            lbl.Text = "X-Axis";
                            htcOrdinates.Controls.Add(lbl);
                            htcOrdinates.Width = "10%";
                            htrOrdinates.Controls.Add(htcOrdinates); //1
                            //


                            //X ordinate Drop Down
                            htcOrdinates = new HtmlTableCell();
                            DropDownList ddlX = new DropDownList();
                            ddlX.SelectedIndexChanged += new EventHandler(ddlX_SelectedIndexChanged);
                           // ddlX.Attributes.Add("onchange", "javascript:UpdateListBoxes('X','"+i+"');");
                            ddlX.AutoPostBack = true;
                            ddlX.CssClass = "controlFont";
                            ddlX.ID = "axis_column_X_" + i;
                            ddlX.Width = Unit.Pixel(175);
                            if (XList != null)
                            {
                                if (XList.Rows.Count > 0)
                                {
                                    for (int j = 0; j < XList.Rows.Count; j++)
                                    {
                                        ddlX.Items.Add(new ListItem(XList.Rows[j]["Fld"].ToString(), XList.Rows[j]["Val"].ToString()));
                                    }
                                    if (ddlX.Items.Count > 0)
                                    {
                                        if (Xordinates.Count > 0)
                                        {
                                            if (Xordinates[0].Value.Trim() != "")
                                            {
                                                ListItem item = ddlX.Items.FindByValue(Xordinates[0].Value);
                                                if (item != null)
                                                    ddlX.SelectedValue = item.Value;
                                                else
                                                {
                                                    item = ddlX.Items.FindByText(Xordinates[0].Value);
                                                    if (item != null)
                                                        ddlX.SelectedValue = item.Value;
                                                    else
                                                    {
                                                        item = ddlX.Items.FindByValue(Xordinates[0].Text);
                                                        if (item != null)
                                                            ddlX.SelectedValue = item.Value;
                                                        else
                                                        {
                                                            item = ddlX.Items.FindByText(Xordinates[0].Text);
                                                            if (item != null)
                                                                ddlX.SelectedValue = item.Value;

                                                        }
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                if (!Xordinates.Contains(new ListItem(ddlX.Items[0].Text, ddlX.Items[0].Value)))
                                                {
                                                    Xordinates[0].Value = ddlX.Items[0].Value;
                                                    Xordinates[0].Text = ddlX.Items[0].Text;
                                                }
                                            }
                                        }
                                    }
                                    htcOrdinates.Controls.Add(ddlX);
                                }
                            }
                            htcOrdinates.Width = "30%";
                            htrOrdinates.Controls.Add(htcOrdinates); //2
                            //End of X ordinate Drop Down
                        }
                        else
                        {
                            htcOrdinates = new HtmlTableCell();
                            htcOrdinates.Width = "10%";
                            htrOrdinates.Controls.Add(htcOrdinates);
                            htcOrdinates = new HtmlTableCell();
                            htcOrdinates.Width = "10%";
                            htrOrdinates.Controls.Add(htcOrdinates);
                        }


                        htcOrdinates = new HtmlTableCell();
                        htcOrdinates.Width = "10%";
                        htrOrdinates.Controls.Add(htcOrdinates); //3

                        //Y ordinate Label
                        htcOrdinates = new HtmlTableCell();
                        htcOrdinates.Width = "10%";
                        if (i == 0)
                        {
                            Label lblY = new Label();
                            lblY.CssClass = "controlLabelFont";
                            lblY.Text = "Y-Axis";
                            htcOrdinates.Controls.Add(lblY);
                        }
                        htrOrdinates.Controls.Add(htcOrdinates); //4 // Yaxis label
                        // End of Y ordinate Label

                        //Y ordinate Drop Down
                        htcOrdinates = new HtmlTableCell();
                        htcOrdinates.Width = "30%";
                        DropDownList ddlY = new DropDownList();
                        ddlY.CssClass = "controlFont";
                        ddlY.ID = "axis_column_Y_" + i;
                        //ddlY.Attributes.Add("onchange", "javascript:UpdateListBoxes('Y','" + i + "');");
                        ddlY.AutoPostBack = true;
                        ddlY.EnableViewState = true;
                        ddlY.SelectedIndexChanged += new EventHandler(ddlY_SelectedIndexChanged);
                        ddlY.Width = Unit.Pixel(175);
                        if(YList!=null)
                           if (YList.Rows.Count > 0)
                           {
                               for (int j = 0; j < YList.Rows.Count; j++)
                               {
                                   ddlY.Items.Add(new ListItem(YList.Rows[j]["Fld"].ToString(), YList.Rows[j]["Val"].ToString()));
                               }
                               if (ddlY.Items.Count > 0)
                               {
                                   if (YOrdinates.Count > 0)
                                   {
                                       if (YOrdinates[i].Value.Trim() != "")
                                       {
                                           ListItem item = ddlY.Items.FindByValue(YOrdinates[i].Value);
                                           if (item != null)
                                               ddlY.SelectedValue = item.Value;
                                           else
                                           {
                                               item = ddlY.Items.FindByText(YOrdinates[i].Value);
                                               if (item != null)
                                                   ddlY.SelectedValue = item.Value;
                                               else
                                               {
                                                   item = ddlY.Items.FindByValue(YOrdinates[i].Text);
                                                   if (item != null)
                                                       ddlY.SelectedValue = item.Value;
                                                   else
                                                   {
                                                       item = ddlY.Items.FindByText(YOrdinates[i].Text);
                                                       if (item != null)
                                                           ddlY.SelectedValue = item.Value;
                                                   }
                                               }
                                           }
                                       }
                                       else
                                       {
                                           //if (!YOrdinates.Contains(new ListItem(ddlY.Items[i].Text, ddlY.Items[i].Value)))
                                           //{
                                               YOrdinates[i].Value = ddlY.Items[0].Value;
                                               YOrdinates[i].Text = ddlY.Items[0].Text;
                                           //}
                                       }
                                   }
                               }

                               htcOrdinates.Controls.Add(ddlY);
                           }
                        htrOrdinates.Controls.Add(htcOrdinates);//5
                        //End of Y Ordinate Drop Down


                        //Delete and Add Buttons
                        htcOrdinates = new HtmlTableCell();
                        htcOrdinates.Width = "10%";
                        HtmlTable ht = new HtmlTable();
                        ht.CellSpacing = 0;
                        ht.CellPadding = 0;
                        ht.Border = 0;
                        HtmlTableRow htr = new HtmlTableRow();
                        HtmlTableCell htc = new HtmlTableCell();

                        
                        if (i != 0)
                        {

                            ImageButton delButton = new ImageButton();
                            delButton.ID = "del_ordinates_Y_" + i;
                            delButton.ImageUrl = "Images/Delete.GIF";
                            delButton.CausesValidation = false;
                            delButton.OnClientClick = "javascript:DeleteRow('" + i + "')";
                            delButton.Click += new ImageClickEventHandler(delButton_Click);
                            htc.Controls.Add(delButton);
                        }
                        htr.Controls.Add(htc);
                        htc = new HtmlTableCell();
                        if (i == YLength - 1)
                        {
                            ImageButton AddButton = new ImageButton();
                            AddButton.ID = "add_ordinates_Y";
                            AddButton.ImageUrl = "Images/Add.GIF";
                            AddButton.CausesValidation = false;
                            AddButton.OnClientClick = "javascript:AddNewRow();";
                            AddButton.Click += new ImageClickEventHandler(AddButton_Click);
                            htc.Controls.Add(AddButton);
                        }
                        htr.Controls.Add(htc);
                        ht.Controls.Add(htr);
                        htcOrdinates.Controls.Add(ht);


                        htrOrdinates.Controls.Add(htcOrdinates);//6
                        
                        htOrdinates.Controls.Add(htrOrdinates);
                    }
                //}
            //}

            htrOrdinates = new HtmlTableRow();
            htcOrdinates = new HtmlTableCell();
            htcOrdinates.Height = "5px";
            htcOrdinates.ColSpan = 6;
            htrOrdinates.Controls.Add(htcOrdinates);
            htOrdinates.Controls.Add(htrOrdinates);

            
            td_widget_ordinates.Controls.Add(htOrdinates);
        }
        catch
        {

        }
    }

    void ddlY_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            DropDownList ddlY = (DropDownList)sender;
            string strindex = ddlY.ID.Substring(ddlY.ID.LastIndexOf("_") + 1, 1);
            if (ddlY.SelectedValue.Trim() != "")
            {
                int index = Convert.ToInt32(strindex);
                if (lst_Y_axis.Items.Count > 0)
                {
                    lst_Y_axis.Items[index].Value = ddlY.SelectedItem.Value;
                    lst_Y_axis.Items[index].Text = ddlY.SelectedItem.Text;
                }
                else
                {
                    lst_Y_axis.Items.Add(new ListItem(ddlY.SelectedItem.Text, ddlY.SelectedItem.Value));
                }

            }
        }
        catch
        {

        }
    }

    void ddlX_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            DropDownList ddlX = (DropDownList)sender;
            if (ddlX.SelectedValue.Trim() != "")
            {
                if (lst_X_axis.Items.Count > 0)
                {
                    lst_X_axis.Items[0].Value = ddlX.SelectedItem.Value;
                    lst_X_axis.Items[0].Text = ddlX.SelectedItem.Text;
                }
                else
                {
                    lst_X_axis.Items.Add(new ListItem(ddlX.SelectedItem.Text, ddlX.SelectedItem.Value));
                }
            }
        }
        catch
        {
        }
        
    }

    void AddButton_Click(object sender, ImageClickEventArgs e)
    {
        hfAddClick.Value = "0";
        SetDropDownValues();
    }

    void delButton_Click(object sender, ImageClickEventArgs e)
    {
        hfDelClick.Value = "";
        SetDropDownValues();
    }
    private void testCall()
    {
        string[,] xaxis = { { "product", "product" }};
        string[,] yaxis = { { "product", "product" }, { "cost", "cost" }, { "cost1", "cost1" } };

        DataTable dt = new DataTable();
        dt.Columns.Add("Fld");
        dt.Columns.Add("Val");
        dt.Rows.Add("product", "product");
        dt.Rows.Add("cost", "cost");
        dt.Rows.Add("cost1", "cost1");

        //RenderOrdinates(xaxis, yaxis,dt, dt);
    }
    #endregion
    protected void img_Ordinates_Click(object sender, ImageClickEventArgs e)
    {
        //if (td_widget_ordinates.Style["display"] == "none")
        //    td_widget_ordinates.Style["display"] = "block";
        //else
        //    td_widget_ordinates.Style["display"] = "none";

        ////string[,] xaxis = { { "1", "product" } };
        ////string[,] yaxis = { { "1", "product" }, { "2", "cost" }, { "3", "cost1" } };

        //if (lst_X_axis.Items.Count == 0)
        //{
            //lst_X_axis.Items.Add("");
            //lst_Y_axis.Items.Add("");
        //}
        if (CollapsiblePanelExtender1.Collapsed == true)
            CollapsiblePanelExtender1.Collapsed = false;
        else
            CollapsiblePanelExtender1.Collapsed = true;
        RefreshChartTypeImage();

        ////GenerateOrdinates(lst_X_axis.Items,lst_Y_axis.Items);
    }

    private void AddOrdinates()
    {
        try
        {
            //if (Page.IsPostBack)
            //{
                if (hfAddClick.Value == "1")
                {
                    lst_Y_axis.Items.Add("");
                }
            //}
        }
        catch
        {

        }
    }
    private void DeleteOrdinates()
    {
        try
        {
            //if (Page.IsPostBack)
            //{
                if (hfDelClick.Value != "")
                {
                    int index = Convert.ToInt32(hfDelClick.Value);
                    ListItem removeitem = lst_Y_axis.Items[index];
                    lst_Y_axis.Items.Remove(removeitem);
                }
            //}
        }
        catch
        {
        }
    }

    private void SetDefaultItems()
    {
        try
        {
            if (lst_X_axis.Items.Count == 0)
            {
                lst_X_axis.Items.Add("");
                lst_Y_axis.Items.Add("");
            }
        }
        catch
        {
        }
    }

    private void ResetItems()
    {
        try
        {
            if (lst_Y_axis.Items.Count > 1)
            {
                int index = lst_Y_axis.Items.Count - 1;
                for (int i = index; i <= index && i > 0; i--)
                {
                    if (i > 0)
                    {
                        lst_Y_axis.Items.RemoveAt(i);
                    }
                    else if (i == 0)
                    {
                        lst_X_axis.Items[i].Value = "";
                        lst_X_axis.Items[i].Text = "";

                        lst_Y_axis.Items[i].Value = "";
                        lst_Y_axis.Items[i].Text = "";
                    }
                }
            }
            else
            {
                lst_X_axis.Items[0].Value = "";
                lst_X_axis.Items[0].Text = "";

                lst_Y_axis.Items[0].Value = "";
                lst_Y_axis.Items[0].Text = "";
            }
        }
        catch
        {

        }
    }

    private void SetDropDownValues()
    {
        DynamicDisplayI DDI = new DynamicDisplayI();
        try
        {
            if (lst_X_axis.Items.Count > 0)
            {
                for (int i = 0; i < lst_X_axis.Items.Count; i++)
                {
                    Control con = DDI.FindControl(Page.Form.Controls, "axis_column_X_" + i);
                    if (con != null)
                    {
                        DropDownList DDL = (DropDownList)con;
                        DDL.SelectedValue = lst_X_axis.Items[i].Value;
                    }
                }
            }
            if (lst_Y_axis.Items.Count > 0)
            {
                for (int i = 0; i < lst_Y_axis.Items.Count; i++)
                {
                    Control con = DDI.FindControl(Page.Form.Controls, "axis_column_Y_" + i);
                    if (con != null)
                    {
                        DropDownList DDL = (DropDownList)con;
                        DDL.SelectedValue = lst_Y_axis.Items[i].Value;
                    }
                }
            }
        }
        catch
        {

        }
        finally
        {
            DDI = null;
        }
    }
    private bool PerformUpdate(DataSet dsePageInfo, DataSet dseInput)
    {
        HDDatabase HDD = new HDDatabase();
        bool status = false;
        try
        {
            if (dseInput.Tables["p_widgets"] != null)
            {
                string strid = dseInput.Tables["p_widgets"].Rows[0]["af_row_id"].ToString();

                string sql = "delete from sy_widgets where af_row_id = '" + strid + "';delete from sy_widget_ordinates where widget = '" + strid + "'";

                HDD.ExecuteCmdObj(new SqlCommand(sql));

                //status = objMaster.ProcessOperation(dsePageInfo, dseInputInfo, "INSERT");
                status = true;

            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : PerformUpdate :" + ex.Message);
        }
        finally
        {
            HDD = null;
        }
        return status;
    }

    private bool ValidateForAxes(string charttype)
    {
        bool status = false;
        try
        {
            if (charttype.Trim() != "")
            {
                for (int i = 0; i < ChartWithXYAxes.Length; i++)
                {
                    if (ChartWithXYAxes[i].ToLower() == charttype.ToLower())
                    {
                        status = true;
                    }
                }
            }
        }
        catch
        {
        }
        return status;
    }
    protected void ddlSource_SelectedIndexChanged(object sender, EventArgs e)
    {
        RefreshChartTypeImage();
    }
    protected void ddlChartType_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            // Below lines are commanded by 'Imran Gani' on 10-Oct-2012, To get axis for all charts
            //string charttype =ddlChartType.SelectedValue.Trim();
            //if (charttype != "")
            //{
            //    if (!ValidateForAxes(charttype))
            //    {
            //        img_Ordinates.Style["display"] = "none";//Visible = false;
            //        lbl_ordinates.Style["display"] = "none";
            //        td_widget_ordinates.Style["display"] = "none";
            //    }
            //    else
            //    {
            //        //img_Ordinates.Visible = true;
            //        img_Ordinates.Style["display"] = "block";//Visible = false;
            //        lbl_ordinates.Style["display"] = "block";
            //    }
                RefreshChartTypeImage();
            //}
        }
        catch
        {
        }

    }

    private void RefreshChartTypeImage()
    {
        try
        {
            if (ddlChartType.SelectedValue != "")
            {
                if (ddlChartType.SelectedValue.Trim() != "table" && ddlChartType.SelectedValue.Trim() != "text")
                {
                    ImgIcon.Src = "Images/ChartImages/" + ddlChartType.SelectedValue + ".GIF";
                    ImgIcon.Style["display"] = "block";
                    hrefImgTooltip.HRef = "Images/ChartImages/ChartPreview/" + ddlChartType.SelectedValue + ".jpg"; // Added by 'Imran Gani' on 01-Nov-2012, for image preview
                    string ChartType = ddlChartType.SelectedValue.ToLower(); // Added by 'Imran Gani' on 13-Aug-2014, for Dashboard widget property
                    if (ChartType.Contains("pie") || ChartType.Contains("doughnut"))
                        ddlLabelDisplay.Enabled = true;
                    else
                        ddlLabelDisplay.Enabled = false;
                    lblTextContent.Visible = false;
                    txtTextContent.Visible = false;
                    imgTextContentRequired.Visible = false;
                }
                else
                {
                    ImgIcon.Style["display"] = "none";
                    if (ddlChartType.SelectedValue == "text") // Added by 'Imran Gani' on 05-Sep-2014, for Dashboard Text widget
                    {
                        lblTextContent.Visible = true;
                        txtTextContent.Visible = true;                                           
                        txtTextContent.Focus();
                        imgTextContentRequired.Visible = true;
                    }
                    else
                    {
                        lblTextContent.Visible = false;
                        txtTextContent.Visible = false;
                        imgTextContentRequired.Visible = false;
                    }
                }
            }
        }
        catch
        {
        }
    }

    private bool CheckIFSourceChanged()
    {
        bool status = false;
        try
        {
            if (Request.Form != null)
            {
                if (Request.Form["__EVENTTARGET"] != null)
                {
                    if (Request.Form["__EVENTTARGET"].ToString().ToLower().Contains("ddlsource"))
                    {
                        status = true;
                    }
                }
            }
        }
        catch
        {
        }
        return status;
    }
    
}
